package io.terminus.spzx.common.log.aspect;

import io.terminus.spzx.common.log.annotation.SpzxLog;
import io.terminus.spzx.common.log.service.AsyncOperLogService;
import io.terminus.spzx.common.log.utils.LogUtils;
import io.terminus.spzx.model.entity.system.SysOperLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author lichunlong lcl253137@alibaba-inc.com
 * @desc 日志环绕通知切面类
 * @date 2024-10-18
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {

    private final AsyncOperLogService asyncOperLogService;

    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, SpzxLog sysLog) {
        // 构建前置参数
        SysOperLog sysOperLog = new SysOperLog();
        LogUtils.beforeHandleLog(sysLog, joinPoint, sysOperLog);

        Object proceed = null;
        try {
            // 执行业务方法
            proceed = joinPoint.proceed();

            LogUtils.afterHandleLog(sysLog, proceed, sysOperLog, 0, null);
        } catch (Throwable e) {
            LogUtils.afterHandleLog(sysLog, proceed, sysOperLog, 1, e.getMessage());
            throw new RuntimeException(e);
        }

        asyncOperLogService.saveSysOperLog(sysOperLog);

        return proceed;
    }
}
